<template>
	<el-upload
		ref="upload"
		list-type="picture-card"
		:action="uploadUrl"
		:auto-upload="false"
		:data="uploadParams"
		:limit="uploadLimit"
		:accept="uploadAccept"
		:file-list="uploadList"
		:headers="uploadHeaders"
		:on-change="handleUploadChange"
		:on-success="handleUploadSuccess"
		:class="['lib_cover_upload', { hidden_btn: uploadLimit === 1 && uploadList.length > 0 }]"
		:disabled="disabled"
	>
		<i slot="default" class="el-icon-plus"></i>
		<template slot="file" slot-scope="{ file }">
			<img class="el-upload-list__item-thumbnail" :src="file.url" :alt="file.name" />
			<span class="el-upload-list__item-actions" v-if="!disabled">
				<span class="el-upload-list__item-preview" @click="handleOpenPreview(file)">
					<i class="el-icon-zoom-in"></i>
				</span>
				<span class="el-upload-list__item-delete" @click="handleRemoveCover(file)">
					<i class="el-icon-delete"></i>
				</span>
			</span>
		</template>
	</el-upload>
</template>

<script>
export default {
	props: {
		disabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			uploadUrl: `${!window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl}tbSysAttachment/upload`,
			uploadHeaders: { Authorization: this.$local.get('token') },
			uploadParams: { type: 1, showType: 1, category: -1 },
			uploadAccept: '.jpg,.jpeg,.png,.gif',
			uploadLimit: 1,
			uploadList: [],
			coverImage: ''
		};
	},
	watch: {
		coverImage(val) {
			this.$set(this.uploadList, 0, { url: window.staticPath + val });
		}
	},
	mounted() {},
	methods: {
		handleUploadSuccess(res, file, fileList) {
			let datas = !res.data ? {} : res.data[0];
			this.$emit('finish', datas);
		},
		handleUploadChange(file, fileList) {
			this.uploadList = fileList;
		},
		handleOpenPreview(file) {
			this.$emit('preview', file);
		},
		handleRemoveCover(data) {
			let index = this.uploadList.findIndex((item) => item.uid === data.uid);
			this.uploadList.splice(index, 1);
		},
		handleUpload() {
			this.$refs['upload'].submit();
		}
	}
};
</script>

<style lang="scss" scoped>
.lib_cover_upload ::v-deep {
	display: flex;

	.el-upload--picture-card {
		width: 208px;
		height: 117px;
		line-height: 117px;
	}

	&.hidden_btn .el-upload--picture-card {
		display: none;
	}

	.el-upload-list {
		display: flex;

		&.is-disabled {
			filter: grayscale(0.5);
		}
	}

	.el-upload-list__item {
		width: 208px;
		height: 117px;
		margin: 0;
		transition: none;
	}

	.el-upload-list__item-thumbnail {
		object-fit: cover;
	}
}
</style>
